package com.yuufa.test.ex;

public class Ex7 {

    // implements replace
    public static void main(String[] args) {
        
        String source = "one man do something another man";
        String old = "man";
        String target = "person";
        
        String result = replace(source.toCharArray(), old.toCharArray(), target.toCharArray());
        
        System.out.println(result);
    }
    
    public static String replace(char[] source, char[] old, char[] target) {
        
        int index = indexOf(source, old);
        String result = "";
        
        while(index != -1) {
            result += new String(source, 0, index) + new String(target);
            
            int begin = index + old.length;
            int end = source.length - begin;
            
            source = new String(source, begin, end).toCharArray();
            index = indexOf(source, old);
        }
        
        return result + new String(source);
    }

    public static int indexOf(char[] source, char[] target) {

        char first = target[0];
        int slen = source.length;
        int tlen = target.length;
        int max = slen - tlen;

        for (int i = 0; i <= max; i++) {
            if( source[i] != first) {
                while(++i<=max && source[i] != first);
            }
            
            if(i<=max) {
                int j = i + 1;
                int end = i + tlen - 1;
                
                for(int k=1;j<=end && source[j] == target[k];k++, j++);
                
                if(j == ( end + 1)) {
                    return i;
                }
            }
        }
        
        return -1;
    }
}
